package io.yyxx.boot.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.yyxx.boot.business.entity.billDataEntity.*;
import io.yyxx.boot.business.mapper.HotelBillDataMapper;
import io.yyxx.boot.business.service.HotelBillDataService;
import io.yyxx.boot.business.service.TrainBillDataService;
import io.yyxx.boot.util.HotelBillApi;
import io.yyxx.boot.util.LastSyncTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HotelBillDataServiceImpl extends ServiceImpl<HotelBillDataMapper, HotelBillData> implements HotelBillDataService {
    private static final int BATCH_SIZE = 1000;


    @Resource
    private HotelBillApi hotelBillApi;

    @Resource
    private LastSyncTimeUtil lastSyncTimeUtil;


    @Lazy
    @Resource
    private HotelBillDataService hotelBillDataService;
    /**
     * 将获取的航班数据写入数据库,如果有新数据则进行保存
     */
    public void saveToDatabase(BillQueryParams params, String appKey, String corpToken) {
        // 1. 获取API数据,做非空判断
        if (hotelBillApi == null) {
            log.error("FlightBillApi 未正确注入");
            return;
        }
        // 1. 获取API数据,做非空判断
        HotelResponse response = hotelBillApi.queryBillSettlement(params, appKey, corpToken);
        if (response == null) {
            log.info("酒店账单API返回的响应对象为空");
            return;
        }

        HotelModule module = response.getModule();
        if (module == null) {
            log.info("酒店账单API返回的模块对象为空");
            return;
        }

        List<HotelBillData> hotelBillData = module.getDataList();
        if (hotelBillData == null || hotelBillData.isEmpty()) {
            log.info("酒店账单API返回的酒店订单数据列表为空或无数据");
            return;
        }

        // 2. 过滤已存在数据
        List<HotelBillData> filteredBills = filterExistingBills(hotelBillData);

        // 3. 批量保存新数据
        if (!filteredBills.isEmpty()) {
            // 遍历列表，为每条数据添加当前时间
            filteredBills.forEach(bill -> {
                bill.setCreateTime(LocalDateTime.now());  // 设置当前时间
                bill.setSyncState(0);                   // 设置 syncStatus = 0
            });

            //将数据批量保存
            try {
                boolean saveResult = hotelBillDataService.saveBatch(filteredBills, BATCH_SIZE);
                if (saveResult) {
                    log.info("本次成功保存 {} 条酒店账单记录", filteredBills.size());
                }
            } catch (Exception e) {
                log.error("酒店账单保存失败", e);
            }

        } else {
            log.info("酒店没有新数据需要保存");
        }
        log.info("本次酒店写入数据库中的数据" +filteredBills.toString());
    }

    /**
     * 过滤已存在的账单（根据每条账单的index）
     */
    private List<HotelBillData> filterExistingBills(List<HotelBillData> newBills) {
        // 2. 提取所有Index（去重）
        Set<String> indexs = newBills.stream()
                .map(HotelBillData::getIndex)
                .filter(Objects::nonNull) // 过滤掉null值
                .collect(Collectors.toSet());

        // 3. 如果提取的Index集合为空，直接返回所有账单
        if (indexs.isEmpty()) {
            return newBills;
        }

        // 4. 查询数据库中已存在的Index
        QueryWrapper<HotelBillData> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("`index`") // 只查询需要的字段
                .in("`index`", indexs);

        Set<String> existingTradeNos = baseMapper.selectList(queryWrapper)
                .stream()
                .map(HotelBillData::getIndex)
                .filter(Objects::nonNull) // 再次过滤null
                .collect(Collectors.toSet());

        // 5. 过滤新数据：保留Index不在数据库中的记录
        return newBills.stream()
                .filter(bill -> {
                    String tradeNo = bill.getIndex();
                    // 保留交易号为null的记录，或者不在数据库中的记录
                    return tradeNo == null || !existingTradeNos.contains(tradeNo);
                })
                .collect(Collectors.toList());
    }

    //从数据库中查询酒店账单数据
    @Transactional(rollbackFor = Exception.class)
    public List<HotelBillData> selectHotelBillData() {
        QueryWrapper<HotelBillData> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(
                "check_in_date",
                "checkout_date",
                "traveler_id",
                "department_id",
                "settlement_fee",
                "book_time",
                "id",
                "sync_state",
                "project_name",
                "project_code",
                "apply_id",
                "city",
                "cost_center",
                "cost_center_number",

                "fee_type_desc",
                "settle_type_desc",//结算类型
                "bill_record_time",//入账时间

                "create_time",
                "hotel_name"); // 指定查询的数据库字段名

        //获取最后同步时间
        LocalDateTime lastSyncTime = lastSyncTimeUtil.getLastSyncTime("hotel_last_sync_time");

        List<HotelBillData> hotelBillData = baseMapper.selectList(queryWrapper);

        //在这里对trainBillData集合进行过滤，创建时间晚于lastSyncTime最后同步时间的账单才返回
        // 过滤数据：保留 create_time > lastSyncTime 的记录
        List<HotelBillData> filteredData = hotelBillData.stream()
                .filter(data ->
                        data.getCreateTime() != null &&
                                data.getCreateTime().isAfter(lastSyncTime) &&
                                data.getSyncState() != 1  // 只处理未同步的数据
                )
                .peek(data -> data.setSyncState(1))
                .collect(Collectors.toList());
        if (!filteredData.isEmpty()) {
            //更改状态信息
            updateBatchById(filteredData);
        } else {
            log.info("没有需要从数据库同步的（酒店）账单数据");
        }
        //过滤完折后更新最后同步时间
        lastSyncTimeUtil.updateSyncTimestamp(LocalDateTime.now(), "hotel_last_sync_time");
        return filteredData;
    }
}
